<?php

namespace app\api\controller;

use app\admin\model\GashaponPro;
use app\common\controller\Api;
use app\common\model\Gashapon;
use app\common\model\GashaponMarketing;
use app\common\model\GashaponProducts;
use app\common\model\Guans;
use app\common\model\Notice;
use app\common\model\UserGashaponLog;
use think\Db;
use think\Exception;

/**
 * 扭蛋管理
 */
class Gashapons extends Api
{
    protected $noNeedLogin = ['list','pro','guan'];
    protected $noNeedRight = ['*'];


    /**
     *
     */
    public function guan(){

        $list = Guans::order('id desc')->where('status','normal')->paginate();

        $this->success(__('Get success'),$list);
    }


    /**
     *
     */
    public function list(){

        $id = $this->request->get('gid');
        if(!$id){
            $this->error(__('Invalid parameters'));
        }

        $list = Gashapon::where('guan_id',$id)->where('status','normal')->order('id desc')->paginate();

        $this->success(__('Get success'),$list);
    }

    /**
     * 详情
     */
    public function pro(){
        $id = $this->request->get('id');
        if(!$id){
            $this->error(__('Invalid parameters'));
        }

        $data = Gashapon::
            where('status','normal')
            ->where('id',$id)
            ->with(['products'=>function($q){$q->with('products')->field('title,thump,rating');}])
            ->find();
        if(!empty($data['products'])){
            $data['products']['products']['pic'] = cdnurl($data['products']['products']['pic'],true);
        }
        $this->success(__('Get success'),$data);
    }

    /**
     * 扭蛋
     */
    public function create(){
        $id = $this->request->post('gid');
        if(!$id){
            $this->error(__('Invalid parameters'));
        }

        $data = Gashapon::
            where('status','normal')
            ->where('id',$id)
            ->find();
        if(!$data){
            $this->error(__('No results were found'));
        }

        $user = $this->auth->getUserinfo();
        if(!$user || $user['score'] < $data['money']){
            $this->error(__('Money not enough'));
        }

        //按照本期，随机一个商品，还要排除掉已经拥有的
        $has_Ids = UserGashaponLog::where(['gid'=>$id,'user_id'=>$user['id']])->column('pid');
        if($has_Ids){
            $has_Ids = implode(',',$has_Ids);
        }else{
            $has_Ids = "''";
        }

        $product = Db::query("select * from nd_gashapon_pro WHERE gashapon_id={$id} AND product_id NOT IN ({$has_Ids}) ORDER BY RAND() LIMIT 1");
        if(!$product){
            $this->error(__('All draws for this period have been completed'));
        }
        $productInfo = GashaponProducts::get(['id'=>$product[0]['product_id']]);
//        $send_num = $this->auth->getUserinfo();
        Db::startTrans();
        try {
//            if($send_num){
//                //扣次数
//                $type = 3;
//                \app\common\model\User::where('user_id',$this->auth->id)->dec('send_num',1)->update();
//            }else{
                //先扣钱
                $type = 2;
                \app\common\model\User::score(-$data['money'],$user['id'],'【'.$data['title'].'】抽奖消耗');
                //营销规则
//                $count = UserGashaponLog::where('user_id',$this->auth->id)->count();
//                if($count){
//                    $config = GashaponMarketing::where('num','<=',$count)->where('status',1)->order('id desc')->find();
//                    if($config){
//                        \app\common\model\User::where('user_id',$this->auth->id)->inc('send_num',$config['send'])->update();
//                    }
//                }
//            }
            //写入日志
            $data = [
              'user_id'     => $user['id'],
              'gid'         => $data['id'],
              'pid'         => $product[0]['product_id'],
                'type'      => $type
            ];
            UserGashaponLog::create($data);

            Db::commit();
        }catch (Exception $e)
        {
            Db::rollback();
            $this->error(__('Operation failed').$e->getMessage());
        }
        $productInfo['pic'] = $productInfo['thump'];
        $this->success(__('Congratulations on obtaining'),$productInfo);


    }

    public function oldlist(){
        $id = $this->request->get('id');
        if(!$id){
            $this->error(__('Invalid parameters'));
        }

        $data =  $data = Gashapon::
        where('status','normal')
            ->where('id',$id)
            ->with(['products'=>function($q){$q->with('products')->field('title,thump,rating');}])
            ->find();
        foreach ($data['products'] as $datum)
        {

            $is_use = UserGashaponLog::where(['gid'=>$id,'pid'=>$datum['product_id'],'user_id'=>$this->auth->id])->find();
            $datum['is_use'] = 0;
            if($is_use){
                $datum['is_use'] = 1;
            }
            $datum['products']['pic'] = cdnurl($datum['products']['pic'],true);
        }
        $data['all_num'] = count($data['products']);
        $data['use_num'] = UserGashaponLog::where(['gid'=>$id,'user_id'=>$this->auth->id])->count();
        $data['rate'] = 0;
        if($data['use_num']>0){
            $data['rate'] = round($data['use_num'] / $data['all_num'] * 100 );
        }
        $this->success(__('Get success'),$data);
    }

    public function getGashaponAll(){
        $list = Gashapon::where('status','normal')->order('id desc')->select();
        $this->success(__('Get success'),$list);
    }
}
